using AutoMapper;
using MediatR;
using S.O.Domain.RBAC;
using S.O.Domain.Dto.Output;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;
using S.O.Api.Read.Application.Command.Permission;

namespace S.O.Api.Read.Application.Handler.Permission
{
    public class GetPermissionHandler : IRequestHandler<GetPermissionCommand, APIResult<List<GetPermissionListDto>>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        private readonly IMapper mapper;

        public GetPermissionHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper)
        {
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 获取权限信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<GetPermissionListDto>>> Handle(GetPermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<GetPermissionListDto>> res = new APIResult<List<GetPermissionListDto>>();
            res.Code = APIEnums.Success;
            res.Data = GetTreee(0);
            res.Msg = "��ȡ�ɹ�";
            return Task.FromResult(res);
        }

        private List<GetPermissionListDto> GetTreee(long parentId)
        {
            var permission = permissionRepository.GetALL().Where(x => x.ParentId == parentId).ToList();
            var dto = mapper.Map<List<GetPermissionListDto>>(permission);
            foreach (var item in dto)
            {
                item.Children = GetTreee(item.Id);
            }
            return dto;
        }
    }
}
